package com.yupi.yuojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.yupi.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import com.yupi.yuojcodesandbox.model.JudgeInfo;
import com.yupi.yuojcodesandbox.security.DefaultSecutityManager;
import com.yupi.yuojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class JavaNativeCodeSandOldbox implements CodeSandbox{
    public static final String GLOBAL_CODE_DIR_NAME="tmpCode"; //全局代码存放目录
    public static final String GLOBAL_JAVA_CLASS_NAME="Main.java";//全局类名
    public static final long  TIME_OUT=5000L;
    public static final List<String> blackList=Arrays.asList("Files","exec");
    public static void main(String[] args) {
        JavaNativeCodeSandOldbox javaNativeCodeSandbox = new JavaNativeCodeSandOldbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        String code = ResourceUtil.readStr("testCode/errorCode/SleepError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setInputList(Arrays.asList("1 2","3 4"));
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.setSecurityManager(new DefaultSecutityManager());
        List<String> inputList = executeCodeRequest.getInputList();
        String code= executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //检验代码是否存在敏感词汇
        //运用字典树
//        WordTree wordTree = new WordTree();
//        wordTree.addWords(blackList);
//        FoundWord foundWord = wordTree.matchWord(code);
//        if(foundWord!=null){
//            System.out.println(foundWord.getFoundWord());
//            return null;
//        }

        //1.把用户代码保存为文件
        String userDir=System.getProperty("user.dir");
        String globalCodePathNmae=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在,不存在则新建
        if(!FileUtil.exist(globalCodePathNmae)){
            FileUtil.mkdir(globalCodePathNmae);
        }
        //把用户代码隔离存放
        String userCodeParentPath=globalCodePathNmae+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_JAVA_CLASS_NAME;
        System.out.println(userCodeParentPath);
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2.编译代码,得到class文件
        String compiledCmd=String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        try {
            Process compileProcess=Runtime.getRuntime().exec(compiledCmd);
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess,"编译");
                System.out.println(executeMessage);
        } catch (Exception e) {
          return   getErrorResponse(e);
        }
        //3.代码执行,得到输出结果
        List<ExecuteMessage>executeMessageList=new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd=String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            try{
                Process runProcess=Runtime.getRuntime().exec(runCmd);
                //线程守护安全,超出睡眠时间直接杀死
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了,中断");
                        //销毁进程
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess,"运行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            }catch (Exception e){
                return   getErrorResponse(e);
            }
        }
        //4.收集整理输出
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outPutList=new ArrayList<>();
        //最大运行时间
        long maxTime=0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(1);
                break;
            }
            outPutList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if(time!=null){
                maxTime=Math.max(maxTime,time);
            }
        }
        //正常运行完成
        if(outPutList.size()==executeMessageList.size()){
            executeCodeResponse.setStatus(3);
        }
        executeCodeResponse.setOutputList(outPutList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //5.文件清理,防止服务器空间不足
        if(userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del ? "成功":"失败"));
        }

        return executeCodeResponse;
    }

    public ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
